package com.flydust.apipulse.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.flydust.apipulse.entity.Endpoint;
import com.flydust.apipulse.entity.EndpointDto;
import com.flydust.apipulse.service.EndpointService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
@RequestMapping("/api/endpoints")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class EndpointController {

    private static final Logger logger = Logger.getLogger(EndpointController.class.getName());
    
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private EndpointService endpointService;

    // 获取所有接口
    @GetMapping
    public ResponseEntity<List<Endpoint>> getAllEndpoints() {
        logger.info("获取所有接口列表");
        try {
            List<Endpoint> endpoints = endpointService.findAll();
            return ResponseEntity.ok(endpoints);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取接口列表时发生异常", e);
            throw e;
        }
    }

    // 根据项目ID和可选的目录ID获取接口
    @GetMapping("/project/{projectId}")
    public ResponseEntity<List<Endpoint>> getEndpointsByProjectId(
            @PathVariable Long projectId,
            @RequestParam(required = false) Long directoryId) {
        logger.info("根据项目ID获取接口列表: " + projectId + 
                   (directoryId != null ? ", 目录ID=" + directoryId : ", 全部目录"));
        try {
            List<Endpoint> endpoints;
            if (directoryId != null) {
                if (directoryId == -1) {
                    // 获取默认目录下的接口（directoryId为null的接口）
                    endpoints = endpointService.findByProjectIdAndNullDirectoryId(projectId);
                } else {
                    // 获取指定目录下的接口
                    endpoints = endpointService.findByProjectIdAndDirectoryId(projectId, directoryId);
                }
            } else {
                // 获取项目下的所有接口
                endpoints = endpointService.findByProjectId(projectId);
            }
            return ResponseEntity.ok(endpoints);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "根据项目ID获取接口列表时发生异常，项目ID: " + projectId, e);
            throw e;
        }
    }

    // 根据ID获取接口
    @GetMapping("/{id}")
    public ResponseEntity<Endpoint> getEndpointById(@PathVariable Long id) {
        logger.info("根据ID获取接口: " + id);
        try {
            Optional<Endpoint> endpoint = endpointService.findById(id);
            if (endpoint.isPresent()) {
                return ResponseEntity.ok(endpoint.get());
            } else {
                logger.warning("未找到ID为 " + id + " 的接口");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取接口详情时发生异常，接口ID: " + id, e);
            throw e;
        }
    }

    // 创建接口
    @PostMapping("/project/{projectId}")
    public ResponseEntity<Endpoint> createEndpoint(@PathVariable Long projectId, @RequestBody EndpointDto endpointDto) {
        logger.info("创建接口: " + endpointDto.getName());
        try {
            // 转换DTO为实体
            Endpoint endpoint = new Endpoint();
            endpoint.setName(endpointDto.getName());
            endpoint.setUrl(endpointDto.getUrl());
            endpoint.setMethod(endpointDto.getMethod());
            endpoint.setCheckInterval(endpointDto.getCheckInterval());
            endpoint.setExpectedStatus(endpointDto.getExpectedStatus());
            endpoint.setProjectId(projectId);
            
            // 处理bodyType
            if (endpointDto.getBodyType() != null) {
                endpoint.setBodyType(endpointDto.getBodyType());
            }
            
            // 处理请求头对象，转换为JSON字符串存储
            if (endpointDto.getRequestHeaders() != null && !endpointDto.getRequestHeaders().isEmpty()) {
                try {
                    String headersJson = objectMapper.writeValueAsString(endpointDto.getRequestHeaders());
                    endpoint.setRequestHeaders(headersJson);
                } catch (JsonProcessingException e) {
                    logger.warning("转换requestHeaders为JSON时发生异常: " + e.getMessage());
                }
            }
            
            // 处理请求体对象，转换为JSON字符串存储
            if (endpointDto.getRequestBody() != null) {
                try {
                    String bodyJson;
                    if (endpointDto.getRequestBody() instanceof String) {
                        bodyJson = (String) endpointDto.getRequestBody();
                    } else {
                        bodyJson = objectMapper.writeValueAsString(endpointDto.getRequestBody());
                    }
                    endpoint.setRequestBody(bodyJson);
                } catch (JsonProcessingException e) {
                    logger.warning("转换requestBody为JSON时发生异常: " + e.getMessage());
                }
            }
            
            // 处理params对象，转换为JSON字符串存储
            if (endpointDto.getParams() != null && !endpointDto.getParams().isEmpty()) {
                try {
                    String paramsJson = objectMapper.writeValueAsString(endpointDto.getParams());
                    endpoint.setParams(paramsJson);
                } catch (JsonProcessingException e) {
                    logger.warning("转换params为JSON时发生异常: " + e.getMessage());
                }
            }
            
            endpoint.setTimeout(endpointDto.getTimeout());
            endpoint.setEnabled(endpointDto.getEnabled());
            endpoint.setDirectoryId(endpointDto.getDirectoryId());
            
            Endpoint savedEndpoint = endpointService.save(endpoint);
            return ResponseEntity.ok(savedEndpoint);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "创建接口时发生异常，接口名称: " + endpointDto.getName(), e);
            return ResponseEntity.status(500).build();
        }
    }

    // 更新接口
    @PutMapping("/{id}")
    public ResponseEntity<Endpoint> updateEndpoint(@PathVariable Long id, @RequestBody EndpointDto endpointDto) {
        logger.info("更新接口: " + id);
        try {
            Optional<Endpoint> endpointOpt = endpointService.findById(id);
            if (endpointOpt.isPresent()) {
                Endpoint endpoint = endpointOpt.get();
                endpoint.setName(endpointDto.getName());
                endpoint.setUrl(endpointDto.getUrl());
                endpoint.setMethod(endpointDto.getMethod());
                endpoint.setCheckInterval(endpointDto.getCheckInterval());
                endpoint.setExpectedStatus(endpointDto.getExpectedStatus());
                
                // 处理bodyType
                if (endpointDto.getBodyType() != null) {
                    endpoint.setBodyType(endpointDto.getBodyType());
                }
                
                // 处理请求头对象，转换为JSON字符串存储
                if (endpointDto.getRequestHeaders() != null && !endpointDto.getRequestHeaders().isEmpty()) {
                    try {
                        String headersJson = objectMapper.writeValueAsString(endpointDto.getRequestHeaders());
                        endpoint.setRequestHeaders(headersJson);
                    } catch (JsonProcessingException e) {
                        logger.warning("转换requestHeaders为JSON时发生异常: " + e.getMessage());
                    }
                } else {
                    endpoint.setRequestHeaders(null);
                }
                
                // 处理请求体对象，转换为JSON字符串存储
                if (endpointDto.getRequestBody() != null) {
                    try {
                        String bodyJson;
                        if (endpointDto.getRequestBody() instanceof String) {
                        bodyJson = (String) endpointDto.getRequestBody();
                        } else {
                            bodyJson = objectMapper.writeValueAsString(endpointDto.getRequestBody());
                        }
                        endpoint.setRequestBody(bodyJson);
                    } catch (JsonProcessingException e) {
                        logger.warning("转换requestBody为JSON时发生异常: " + e.getMessage());
                    }
                } else {
                    endpoint.setRequestBody(null);
                }
                
                // 处理params对象，转换为JSON字符串存储
                if (endpointDto.getParams() != null && !endpointDto.getParams().isEmpty()) {
                    try {
                        String paramsJson = objectMapper.writeValueAsString(endpointDto.getParams());
                        endpoint.setParams(paramsJson);
                    } catch (JsonProcessingException e) {
                        logger.warning("转换params为JSON时发生异常: " + e.getMessage());
                    }
                } else {
                    endpoint.setParams(null);
                }
                
                endpoint.setTimeout(endpointDto.getTimeout());
                endpoint.setEnabled(endpointDto.getEnabled());
                endpoint.setDirectoryId(endpointDto.getDirectoryId());
                
                Endpoint savedEndpoint = endpointService.save(endpoint);
                return ResponseEntity.ok(savedEndpoint);
            } else {
                logger.warning("未找到ID为 " + id + " 的接口进行更新");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "更新接口时发生异常，接口ID: " + id, e);
            return ResponseEntity.status(500).build();
        }
    }

    // 删除接口
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteEndpoint(@PathVariable Long id) {
        logger.info("删除接口: " + id);
        try {
            Optional<Endpoint> endpoint = endpointService.findById(id);
            if (endpoint.isPresent()) {
                endpointService.deleteById(id);
                return ResponseEntity.noContent().build();
            } else {
                logger.warning("未找到ID为 " + id + " 的接口进行删除");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "删除接口时发生异常，接口ID: " + id, e);
            throw e;
        }
    }
}